<template>
  <div class="visitor-index">
    <a-row class="aRow-wrapper" :gutter="12">
      <a-col class="tree-wrapper" :span="4">
        <left-tree @onSelect="onTreeSelected"></left-tree>
      </a-col>
      <a-col class="listContent-wrapper" :span="20">
        <div class="title-wrapper-box">
          <top-title :updateTime="true" :content="content"></top-title>
          <div style="display: flex; align-items: center; gap: 0.1rem">
            <div v-if="isPoliceAgencyId.isChildren == false" class="add-btns cursor" @click="handelAdd">新增</div>
            <a-upload
              name="file"
              :showUploadList="false"
              :multiple="false"
              accept=".xls,.xlsx,"
              :action="importExcelUrl"
              :customRequest="customRequest"
            >
              <div v-if="isPoliceAgencyId.isChildren == false" class="add-btns cursor">批量导入</div>
            </a-upload>

            <div v-if="isPoliceAgencyId.isChildren == false" class="add-btns cursor" @click="handleTemplateDownload">
              模板下载
            </div>
          </div>
        </div>
        <!--   <div class="tabss">
          <div class="tab" :class="{ active: activeIndex == 0 }" @click="activeIndex = 0">不良行为未成年人</div>
          <div class="tab" :class="{ active: activeIndex == 1 }" @click="activeIndex = 1">高风险青壮年</div>
        </div> -->
        <!--  <div class="cadd-btn cursor" @click="handelAdd">新增</div> -->

        <div class="l-w_content" style="margin-top: 28px">
          <!-- <div class="tabs">
            <div class="tab">不良行为未成年人</div>
            <div class="tab">高风险青壮年</div>
          </div> -->
          <div class="l-w_c_content">
            <div class="pageInfo">
              <list
                ref="listRef"
                :idCode="selectedKey"
                :villageList="villageList"
                :institution="selectedData"
                :activeIndex="activeIndex"
                :youthIds="youthIds"
                :caseSelectValue="caseSelectValue"
              ></list>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <Add ref="addRef" :institution="selectedData" @refresh="onRefresh" />
    <AddAdults ref="addAdultsRef" :institution="selectedData" @refresh="onRefresh" />
  </div>
</template>

<script>
import leftTree from '@/components/leftTree'
import topTitle from '@/components/topTitle'
import list from './modules/list'
import Add from './modules/add.vue'
import AddAdults from '../youngAdultsProfile/modules/add'
import { getCommunityList, excelImport } from '@/api/api'
import { getAction } from '@/api/manage'
import axios from 'axios'

import { mapState } from 'vuex'
import { Link } from 'element-ui'

export default {
  name: 'pringing',
  components: { leftTree, topTitle, list, Add, AddAdults },
  data() {
    return {
      content: [['人员列表']],
      loading: false,
      activeKey: '1',
      key: '',
      selectedKey: '',
      villageList: [],
      addRef: null,
      jurisdictionList: [],
      selectedData: {},
      activeIndex: 0,
      addAdultsRef: null,
      selectedKey: '',
      url: {
        importExcelUrl: '/excel/uploadQnMinor',
      },
      options: {},
      youthIds: [],
      yvalue: '',
      caseSelectValue: [],
    }
  },
  provide() {
    return {
      provideData: () => {
        return {
          jurisdictionList: this.jurisdictionList,
        }
      },
    }
  },
  computed: {
    ...mapState({
      isPoliceAgencyId: (state) => state.user.isPoliceAgencyId,
    }),
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    this.youthIds = JSON.parse(this.$route.query.youthIds || '[]')
    this.options = this.$route.query
    const val = this.options.value.split(',')

    this.caseSelectValue = this.youthIds.map((id) => [...val, id])

    this.activeKey = this.$route.query.activeKey ? this.$route.query.activeKey : '1'
  },
  methods: {
    handelClick(event) {
      this.activeKey = event
      this.searchTableData()
    },
    onTreeSelected(selectedKeys, selectedData) {
      console.log(selectedKeys, selectedData, '选择派出所')
      this.selectedKey = selectedKeys
      this.selectedData = selectedData
      this.selectedKey = Array.isArray(selectedKeys) ? selectedKeys[0] : ''
      if (this.selectedKey) {
        this.searchTableData()
        this.loadDataWithTree({
          policeAgencyId: this.selectedKey,
        })
      }
      this.get_police_list()
    },
    searchTableData() {
      this.$nextTick(() => {
        // 调用各个组件的 search 方法
        this.$refs.listRef.searchQuery()
      })
    },
    async loadDataWithTree(treeNode) {
      const { policeAgencyId } = treeNode
      try {
        let res = await getCommunityList({
          policeAgencyId,
        })
        if (res.code == 200) {
          this.villageList = res.result
        }
      } catch (error) {
        console.log(error)
      } finally {
      }
    },
    handelAdd() {
      console.log(this.activeIndex)
      if (this.activeIndex == 0) {
        this.$refs.addRef.show()
      } else {
        this.$refs.addAdultsRef.show()
      }
    },
    async get_police_list() {
      let policeAgencyId = this.isPoliceAgencyId.id
      this.jurisdictionLoading = true
      let {
        result: { records },
      } = await getAction('/police/jurisdiction/list', { policeAgencyId, pageSize: 99999 })
      this.jurisdictionLoading = false
      this.jurisdictionList = records.map((item) => ({
        id: item.id,
        jurisdictionName: item.jurisdictionName,
        principalPoliceUser: item.principalPoliceUser ? item.principalPoliceUser.name : '暂无',
      }))
    },
    onRefresh() {
      this.$refs.listRef.searchReset()
    },
    async downLoadMinioExcels(files) {
      for (const f of files) {
        const res = await axios.get(f.url, { responseType: 'blob' })
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = f.name
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
    },
    handleTemplateDownload() {
      const files = [
        { name: '预防未成年人违法犯罪.xlsx', url: 'http://92.203.19.60:9000/law/template/预防未成年人违法犯罪.xlsx' },
        { name: '个人极端及群体性事件.xlsx', url: 'http://92.203.19.60:9000/law/template/个人极端及群体性事件.xlsx' },
        { name: '涉稳涉访.xlsx', url: 'http://92.203.19.60:9000/law/template/涉稳涉访.xlsx' },
        { name: '防重案命案.xlsx', url: 'http://92.203.19.60:9000/law/template/防重案命案.xlsx' },
      ]
      this.downLoadMinioExcels(files)
        .then(() => this.$message.success('已发起下载'))
        .catch((err) => console.log('下载模板失败', err))
    },
    async customRequest(info) {
      console.log(info, 'infossssss')
      let file = info.file
      const formData = new FormData()
      // formData.append('file', file)
      //formData.append('type', 2)
      formData.append('excelFile', file)
      formData.append('policeAgencyId', this.selectedKey)
      let res = await excelImport(formData)
      console.log(res, 'resres')
      if (res.code == 200) {
        this.imageUrl = [res.result]
        this.fileList = [res.result].map((item, index) => {
          return {
            uid: index,
            status: 'done',
            url: item.fullPath,
          }
        })

        // 上传完成之后，隐藏上传框
        let uploadDom = this.$refs.uploadImgRef.$el.getElementsByClassName('ant-upload-select-picture-card')[0]
        uploadDom.style.display = 'none !important'
      }
    },

    handleImportExcel(info) {
      console.log(info, 'info999')
      this.loading = true
      if (info.file.status !== 'uploading') {
        console.log('上传中')
      }
      if (info.file.status === 'done') {
        this.loading = false
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName },
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (
                <div>
                  {' '}
                  <span> {msg} </span>
                  <br />{' '}
                  <span>
                    {' '}
                    具体详情请{' '}
                    <a href={href} target="_blank" download={fileName}>
                      {' '}
                      点击下载{' '}
                    </a>{' '}
                  </span>{' '}
                </div>
              ),
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.loading = false
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              },
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
  },
}
</script>
<style lang="less" scoped>
.visitor-index {
  width: 100%;
  height: 100%;
  .pageInfo {
    width: 100%;
    height: 100%;
  }
  .title-wrapper-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .tabss {
    display: flex;
    align-items: center;
    position: absolute;
    width: 500px;
    height: 30px;

    top: 6%;
    left: 2%;
    .tab {
      width: 140px;
      height: 30px;

      border: 0.01rem solid var(--theme-input-border);
      color: #8fbbff;
      text-align: center;
      line-height: 30px;
      background: #06409a;
    }
    .active {
      background: #1970f6;
      color: #fff;
    }
  }
  .tab:last-child {
    border-left: none;
  }
  .cadd-btn {
    width: 80px;
    height: 30px;
    color: #fff;
    background: #1970f6;
    text-align: center;
    line-height: 30px;
    font-size: 16px;
    position: absolute;
    top: 6%;
    right: 5%;
    border-radius: 8px;
  }
  .add-btns {
    // position: absolute;
    // top: 0.16rem;
    // right: 0.2rem;
    width: 1rem;
    height: 0.4rem;
    background: #1388ff;
    border-radius: 0.04rem;
    font-size: 0.16rem;
    font-weight: bold;
    color: #0b3f73;
    line-height: 0.4rem;
    text-align: center;
  }
}
</style>
